package com.serene.im.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * netty 服务
 *
 * @author serene
 * @date 2021/3/18 15:55
 */
@Component
public class NettyServer {

    private static final Logger log = LoggerFactory.getLogger(NettyServer.class);

    /**
     * netty端口
     */
    private static int port = 8080;

    private static class SingletionWSServer {
        static final NettyServer instance = new NettyServer();
    }

    public static NettyServer getInstance() {
        return SingletionWSServer.instance;
    }

    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;
    private ServerBootstrap server;
    private ChannelFuture future;


    /**
     * 处理客户端请求
     */
    public NettyServer() {
        System.out.println("1.进入NettyServer");
        mainGroup = new NioEventLoopGroup();
        subGroup = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyChannelInitializer());
    }

    /**
     * 启动netty
     */
    public void start() {
        this.future = server.bind(port);
        log.info("netty server server 启动完毕... port = " + port);
        System.out.println("future-> " + future.isSuccess());
        System.out.println("3.启动netty服务");
    }

}
